document.addEventListener("DOMContentLoaded", function() {
    // Get selected text and its answer from background.js
    chrome.runtime.sendMessage({ message: "get_selected_text" }, function(response) {
        if (chrome.runtime.lastError) {
            console.error('Error sending message:', chrome.runtime.lastError);
            return;
        }

        if (response && response.selectedText) {
            addMessageToChat("user", response.selectedText);
            addMessageToChat("assistant", response.answer);
        }
    });

    // Handle send button click
    document.getElementById("sendButton").addEventListener("click", function() {
        const userInput = document.getElementById("userInput");
        const inputValue = userInput.value.trim();
        if (inputValue) {
            addMessageToChat("user", inputValue);
            // Send user input to the background script for processing
            chrome.runtime.sendMessage({ message: "popup_chat", data: inputValue }, function(response) {
                if (chrome.runtime.lastError) {
                    console.error('Error sending message:', chrome.runtime.lastError);
                    return;
                }
                addMessageToChat("assistant", response.answer);
                userInput.value = '';
            });
        }
    });
});

function addMessageToChat(role, message) {
    const chatOutput = document.getElementById("chatOutput");
    const messageDiv = document.createElement("div");
    messageDiv.className = "message " + role;
    messageDiv.innerText = message;
    chatOutput.appendChild(messageDiv);
    if (role === "assistant") {
        const splitLineEnd = document.createElement("hr");
        splitLineEnd.color = "#9a9a9a"
        splitLineEnd.align = "right"
        splitLineEnd.width = "20%"
        chatOutput.appendChild(splitLineEnd);
    }
}
